layui.use(['tree','table','treeGrid','layer','jquery'],function(){

    var $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;


    //列表数据
    var option = {
        elem: '#tableList',
        url : '/admin/product/getProductList',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 15,
        id : "listTable",
        loading:true,
        cols : [[
            {type: "checkbox", fixed:"left", width:50},
            {field: 'categoryName', title: '类别名', align:'center',minWidth:150,templet:function (d){
                    var name = null;
                    $.ajax({
                        url:"/admin/productCategory/getProductCategory?ProductCategoryId="+d.categoryId,
                        type:'GET',
                        async:false,
                        success:function (data){
                            name = data.name;
                        }
                    });
                    return name;

                }
            },
            // {field: 'produceId', title: '商品标识', align:'center',minWidth:150},
            {field: 'produceName', title: '商品名称', minWidth: 200, align: 'center'},
            {field: 'supplier', title: '供货公司', align: 'center'},
            {field: 'produceNo', title: '货号', sort: true, minWidth: 100, align: "center"},
            {
                field: '', title: '供货日期', align: 'center', minWidth: 180, sort: true, templet: function (d) {
                    //处理时间
                    var date = new Date(d.supplyDate);
                    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                }
            },
            {field: 'buyer', title: '购买人', sort: true, minWidth: 100, align: "center"},
            {field: 'buyNum', title: '购买数量', sort: true, minWidth: 100, align: "center"},
            {field: 'unit', title: '数量单位', align: 'center', minWidth: 150},
            {field: 'price', title: '金额', sort: true, minWidth: 100, align: "center"},
            {
                field: 'storageId', title: '存放位置', align: 'center', minWidth: 150, templet: function (d) {
                    var name = null;
                    $.ajax({
                        url: "/admin/storage/getStorage?StorageId=" + d.storageId,
                        type: 'GET',
                        async: false,
                        success: function (data) {
                            name = data.name;
                        }
                    });
                    return name;
                }
            },
            /*{field: 'unit', title: '领用人', align:'center',minWidth:150},
            {field: 'unit', title: '领用数量', align:'center',minWidth:150},*/
            {
                field: 'remainNum', title: '余货量', align: 'center', minWidth: 150, templet: function (d) {
                    var name = null;
                    $.ajax({
                        url: "/admin/productUsed/totalUsed?productId=" + d.produceId,
                        type: 'GET',
                        async: false,
                        success: function (data) {
                            name = data;
                        }
                    });
                    return name;
                }
            },
            /*{field: 'unit', title: '备注', align:'center',minWidth:150},*/
            /*{field: 'userId', title: '领用人', align:'center',minWidth:150},
            {field: 'useNum', title: '领用数量', align:'center',minWidth:150},
            {field: 'usedRemainNum', title: '使用后剩余量', align:'center',minWidth:150},*/
            {field: '88', title: '操作', minWidth: 175, templet: '#tableListBar', fixed: "right", align: "center"}
        ]],
        done: function (res, curr, count) {
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
            $("[data-field='produceName']").children().each(function (i, ele) {
                if (i == 0)
                    return;
                if ($("[data-field='remainNum']").children()[i].innerHTML - res.data[i - 1].threshold <= 0) {
                    var name = ele.innerHTML;
                    var remain = $("[data-field='remainNum']").children()[i].innerHTML;
                    $("[data-field='remainNum']").children()[i].innerHTML = "<b style='color: red'>" + remain + "</b>";
                    ele.innerHTML = "<b style='color: red'>" + name + "</b>";
                }
            });
            //$('#tableList').next().find('.layui-table-body').find("table" ).find("tbody").children("tr").on('dblclick',function(){
            var data;
            table.on('rowDouble(tableList)', function (obj) {
                data = obj.data;
                layui.layer.open({
                    title: '信息详情'
                    , type: 2
                    , resize: false
                    , area: ['600px', '630px']
                    , shadeClose: true
                    , content: "productDetails.jsp?id=" + data.produceId
                });
            })
            // })

        }
    };

    //设备列表
    var tableIns = table.render(option);




    //场景数据
    var height = $(document).height();
    $(".orgbox").css('height', (height - 40) + "px");
    $(window).on("resize", function () {
        $(".orgbox").css('height', (height - 40) + "px");
    });
    var treeData = {
        elem: '#tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调
            option.url = '/admin/product/getProductListByCate';
            option.where = {categoryId: item.id};
            table.render(option);
        },
        nodes: null
    };

    $.get('/admin/productCategory/menu', function (data) {
        treeData.nodes = data.data;
        layui.tree(treeData);
    });


    //搜索设备信息
    $(".search_btn").on("click", function () {
        var searchKey = $(".searchVal").val();
        if (searchKey != '') {
            option.url = '/admin/product/search';
            option.method = 'post';
            option.where = {keyword: searchKey};
            table.render(option);
            //权限时候添加类名  layui-btn-disabled


        } else {
            layer.msg("请输入搜索的内容");
        }
    });




    const IntervalId = setInterval(() => {
        if ($(".addNews_btn").length != 0) {
        //添加设备
        $(".addNews_btn").click(function () {
            var index = layui.layer.open({
                title: "添加产品",
                type: 2,
                content: "produceAdd.jsp",
                area: ['100%', '100%'],
                success: function () {
                    //这里可以有写成功后的其他操作
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回记录列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500)
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize", function () {
                layui.layer.full(index);
            });
        });
        //批量添加addExcel
        layui.use('upload', function(){
            var upload = layui.upload;
            //执行实例
            var uploadInst = upload.render({
                elem: '#addConsumableExcel' //绑定元素
                ,field: 'uploadFile'
                ,url: '/admin/product/addConsumableExcel' //上传接口
                ,acceptMime:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel.sheet.macroEnabled.12'
                ,accept:'file'
                ,done: function(res) {
                    //上传完毕回调
                    layer.open({
                        content: '共需要添加' + res.count + '条记录'
                        , btn: ['确认添加', '取消']
                        , yes: function (index, layero) {
                            console.log(res.data)
                            //按钮【按钮一】的回调
                            var a = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});
                            top.layer.close(a);
                            top.layer.msg("数据添加成功！");
                            //刷新页面
                            tableIns.reload();
                            layer.close(index)
                        }
                        , btn2: function (index, layero) {
                            $.get("/admin/product/batchdelete", {
                                ids: res.data  //将需要删除的newsId作为参数传入
                            }, function (data) {
                                if (data.code == 200) {
                                } else {
                                    layer.msg("数据添加异常！请重试");
                                }
                                layer.close(index);
                            })
                        }
                    })
                }
            });
        });


        //批量删除
        $(".delAll_btn").click(function () {
            var checkStatus = table.checkStatus('listTable'),//此处的id为table数据格式中的id
                data = checkStatus.data,
                idArr = [];
            if (data.length > 0) {
                for (var i in data) {
                    idArr.push(data[i].produceId);
                }
                layer.confirm('确定删除选中的产品记录？', {icon: 3, title: '提示信息'}, function (index) {
                    $.get("/admin/product/batchdelete", {
                        ids: idArr  //将需要删除的newsId作为参数传入
                    }, function (data) {
                        if (data.code == 200) {
                            layer.msg("删除成功！");
                        } else {
                            layer.msg("删除失败，请重试！");
                        }
                        tableIns.reload();
                        layer.close(index);
                    })

                })
            } else {
                layer.msg("请选择需要删除的记录");
            }
        });
        clearInterval(IntervalId);
}
},0);
    //列表操作
    table.on('tool(tableList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;
        if (layEvent === 'edit' && $('#edit').hasClass('layui-btn-disabled') === false) { //编辑
            var index = layui.layer.open({
                title: "修改产品信息",
                type: 2,
                content: "/admin/views/product/productEdit.jsp?id=" + data.produceId,
                area: ['100%', $(document).height() - 30 + 'px'],
                success: function () {
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            });
        } else if (layEvent === 'del' && $('#del').hasClass('layui-btn-disabled') === false) { //删除
            layer.confirm('确定删除此记录吗？', {icon: 3, title: '提示信息'}, function (index) {
                $.get("/admin/product/delete?id=" + data.produceId, function (data) {
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                });
            });
        }
    });

});